package cn.wolfcode.rbac.interptor;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.util.RequiredPermission;
import cn.wolfcode.rbac.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public class SecurityIntercptor extends HandlerInterceptorAdapter {
    /**
     * 返回值如果是true表示方形
     *  如果是false表示拦截
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1 判断用户是否是超级管理员
        Employee employee = UserContext.getCurrent();
        if(employee.getAdmin()){
            return true;
        }
        // 2 看方法上是否拥有@RequiredPermission注解(有注解表示有权限，无注解表示没有权限)
        // 如果获取到你正在访问方法上的注解呢？
        HandlerMethod hm = (HandlerMethod) handler;
        System.out.println(hm);
        Method method = hm.getMethod();
        RequiredPermission requiredPermission = method.getAnnotation(RequiredPermission.class);
        if(requiredPermission == null){
            return true;
        }
        //如果方法有注解，上session中吧用户所拥有的权限表达式拿出来
        List<String> expressions = UserContext.getExpressions();
        if(expressions.contains(requiredPermission.value()[1])){
            return true;
        }
        //跳转到 没有权限的界面中
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        return false;
    }
}
